package com.shop.cereshop.app.controller.qrcode;

import com.shop.cereshop.app.utils.ImageUtil;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.qrcode.QRCodeQueryParam;
import com.shop.cereshop.commons.domain.qrcode.QRCodeRespond;
import com.shop.cereshop.commons.domain.qrcode.QrCodeTypeEnum;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.utils.QRCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;

@RestController(value = "qrCode")
@Api(value = "QRCodeController", tags = "二维码相关接口")
public class QRCodeController {

    /**
     * 获取二维码
     *
     * @param qrCodeQueryParam 二维码参数
     * @return 二维码图片base64
     * @throws Exception
     */
    @ApiOperation(value = "获取二维码")
    @PostMapping("getQrCode")
    public Result<QRCodeRespond> getQrCode(QRCodeQueryParam qrCodeQueryParam) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(qrCodeQueryParam.toString(), null, false);
        String base64Image = ImageUtil.genQrCodeBase64ByBufferedImage(image);
        QRCodeRespond<Object> build = QRCodeRespond.builder()
                .data(base64Image)
                .message(QrCodeTypeEnum.getName(qrCodeQueryParam.getType()))
                .requestId(qrCodeQueryParam.getRequestId())
                .type(QrCodeTypeEnum.getEnum(qrCodeQueryParam.getType()))
                .build();
        return new Result<QRCodeRespond>(build, CoReturnFormat.SUCCESS);
    }
}
